/*
 * Project: matm-commons-test
 * 
 * Created: 10-02-2011
 *
 * $HeadURL$
 * $Id$
 *
 * Copyright (c) 2011 First Data Polska S.A.. All rights reserved.
 */
package pl.com.britenet.myredmine.commons.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hsqldb.Server;
import org.hsqldb.ServerConfiguration;
import org.hsqldb.persist.HsqlProperties;

/**
 * Utility to start and stop the test HSQL server.
 * 
 * @author  <a href="mailto:marcin.maliszewski@britenet.com.pl">Marcin Maliszewski</a>
 * 
 */
public final class HSQLDBServerUtil {

    /**
     * Logger for class <code>pl.firstdata.matm.dao.share.util.HSQLDBServerUtil</code>.
     */
    private static final Log LOG = LogFactory.getLog(HSQLDBServerUtil.class);

    /**
     * The one and only instance of the class.
     */
    private static final HSQLDBServerUtil INSTANCE = new HSQLDBServerUtil();

    /**
     * HSQLServer default port.
     */
    private static final int HSQLSERVER_PORT_DEFAULT = 9001;

    /**
     * Reference to the HSQLDB server.
     */
    private Server hsqlServer;

    /**
     * Private constructor.
     */
    private HSQLDBServerUtil() {

    }

    /**
     * Getter for the single instance of the class.
     * 
     * @return The single instance of the class.
     */
    public static HSQLDBServerUtil getInstance() {
        return INSTANCE;
    }

    /**
     * Starting the HSQLDBServer server.
     * 
     * @param dbName
     *            The name of database.
     * @param port
     *            HSQLDBServer server port.
     */
    public void startServer(final String dbName, final int port) {
        HsqlProperties props = new HsqlProperties();
        props.setProperty("server.port", port);
        props.setProperty("server.database.0", dbName);
        props.setProperty("server.dbname.0", dbName);

        ServerConfiguration.translateDefaultDatabaseProperty(props);

        hsqlServer = new Server();
        hsqlServer.setRestartOnShutdown(false);
        hsqlServer.setNoSystemExit(true);
        hsqlServer.setProperties(props);
        LOG.info("The HSQLDBServer is configured.");

        LOG.info("HSQLDBServer starting. Port: " + hsqlServer.getPort() + ", database: "
                + hsqlServer.getDatabaseName(0, true) + ".");
        hsqlServer.start();
        LOG.info("HSQLDBServer starting - done.");
    }

    /**
     * Starting the HSQLDBServer server.
     * 
     * @param dbName
     *            The name of database.
     */
    public void startServer(final String dbName) {
        startServer(dbName, HSQLSERVER_PORT_DEFAULT);
    }

    /**
     * Shutting down the started server.
     */
    public void stopServer() {
        LOG.info("HSQLDBServer shutting down.");
        hsqlServer.stop();
        LOG.info("HSQLDBServer shutting down - done.");
    }

}